package cn.doitedu.visualiz.platform.controller;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellScanner;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
public class HelloController {
    Connection conn = null;

    // hbase数据库连接只需要创建一次，所以在此构造
    public HelloController() throws IOException {
        Configuration conf = HBaseConfiguration.create();
        conf.set("hbase.zookeeper.quorum","doitedu01:2181,doitedu02:2181,doitedu03:2181");
        conn = ConnectionFactory.createConnection(conf);
    }

    @RequestMapping("/hello")
    public String hello(String name) {
        return "hello " + name;
    }


    @RequestMapping("/api/v1/session")
    public List<String> getSessions(String startDt, String endDt) {
        ArrayList<String> sessions = new ArrayList<>();

        try {

            Table table = conn.getTable(TableName.valueOf("session_view"));
            Scan scan = new Scan();
            scan.withStartRow(startDt.getBytes(),true);
            scan.withStopRow(endDt.getBytes(),false);

            ResultScanner scanner = table.getScanner(scan);

            Iterator<Result> iter = scanner.iterator();



            while(iter.hasNext()){
                Result result = iter.next();
                CellScanner cellScanner = result.cellScanner();
                cellScanner.advance();
                Cell cell = cellScanner.current();
                String json = new String(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
                sessions.add(json);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return sessions;
    }
}
